import { useAppSelector } from '@/store';
import {
  getArticleListAction,
  updateArticleListAction,
} from '@/store/action/article';
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';

import ArticleItem from '@/components/ArticleItem/index';
import styles from './index.module.scss';
import { InfiniteScroll, PullToRefresh } from 'antd-mobile';

export default function ArticleList(props: { id: number }) {
  const { channelId, articles } = useAppSelector((state) => state.article);

  const results = articles[channelId]?.results || [];
  const pre_timestamp = articles[channelId]?.pre_timestamp;

  const dispatch = useDispatch();
  useEffect(() => {
    if (Number(channelId) !== props.id) return;
    if (results.length) return;
    dispatch(
      getArticleListAction({
        channel_id: Number(channelId),
        timestamp: Date.now(),
      })
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [channelId, dispatch]);

  const handleLoadMore = async () => {
    await dispatch(
      updateArticleListAction({
        channel_id: Number(channelId),
        timestamp: Number(pre_timestamp),
      })
    );
  };

  const haandleRefresh = async () => {
    await dispatch(
      getArticleListAction({
        channel_id: Number(channelId),
        timestamp: Date.now(),
      })
    );
  };

  return (
    <div className={styles.root}>
      <PullToRefresh onRefresh={haandleRefresh}>
        <div
          className="article-list"
          style={{ display: Number(channelId) !== props.id ? 'none' : 'block' }}
        >
          {!!results.length &&
            results.map((item, index) => (
              <ArticleItem article={item} key={index} />
            ))}
          <InfiniteScroll
            loadMore={() => handleLoadMore()}
            hasMore={!!pre_timestamp}
          />
        </div>
      </PullToRefresh>
    </div>
  );
}
